import os
import uuid
from datetime import datetime
import os
from PIL import Image
from io import BytesIO
from django.core.files.base import ContentFile
from django.db import models
from django.utils import timezone


def generate_image_filename(instance, filename):
    # 生成唯一文件名，扩展名保持不变
    timestamp = str(int(timezone.now().timestamp() * 1000))
    unique_filename = f"{timestamp}_{uuid.uuid4().hex}.webp"
    return os.path.join('files', unique_filename)


def generate_image_filename1(self, filename):
    # 获取文件扩展名
    ext = os.path.splitext(filename)[-1].lower()
    # 生成新的唯一文件名
    new_filename = f"{uuid.uuid4().hex}{ext}"
    # 返回新的文件路径
    return os.path.join('picture', 'avatarUrl', new_filename)


class User(models.Model):
    user_openid = models.CharField(unique=True, max_length=100, blank=True, null=True)
    user_nick = models.CharField(max_length=30, default="微信用户", verbose_name='用户昵称')
    user_tele = models.CharField(max_length=11, null=True, blank=True, verbose_name='用户电话')
    user_info = models.TextField(max_length=50, null=True, blank=True, verbose_name='个人简介')
    user_image = models.ImageField(upload_to='', verbose_name='头像',
                                   default="picture/avatarUrl/0.png")
    user_address = models.CharField(max_length=50, default="", verbose_name='用户居住地址', null=True, blank=True)
    user_freq = models.IntegerField(default=0, verbose_name='用户访问次数')

    class Meta:
        managed = True
        db_table = "User"

    def save(self, *args, **kwargs):
        # 只有在 user_image 存在时才处理
        if self.user_image:
            # 生成新的文件名
            new_filename = generate_image_filename1(self, self.user_image.name)
            # 更新文件路径（即修改文件名）
            self.user_image.name = new_filename

        super().save(*args, **kwargs)


class Manager(models.Model):
    # 尚未增加session key
    manager_name = models.CharField(max_length=20, verbose_name='管理员姓名', null=True)
    manager_tele = models.CharField(max_length=11, verbose_name='管理员电话', null=True)
    manager_account = models.CharField(max_length=30, verbose_name='管理员用户名', default='admin')
    manager_code = models.CharField(max_length=128, verbose_name='管理员用户密码')
    role = models.BooleanField(null=False, blank=False, default=False)

    class Meta:
        managed = True
        db_table = "Manager"


class Suggestion(models.Model):
    sugg_sub_id = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='问题提交人id')
    sugg_id = models.CharField(max_length=50, unique=True, editable=False, verbose_name='表单id')
    sugg_name = models.CharField(max_length=20, null=False, verbose_name='问题提交人姓名')
    sugg_user_tele = models.CharField(max_length=11, null=True, verbose_name='问题提交人电话')
    sugg_text = models.TextField(max_length=100, null=True, verbose_name='问题描述')
    sugg_title = models.CharField(max_length=20, verbose_name='建议标题', blank=True, null=True)
    sugg_site = models.CharField(max_length=100, null=False, verbose_name='问题地址')
    sugg_sub_time = models.DateTimeField(null=True, blank=True, verbose_name='问题时间', default=timezone.now)
    sugg_handle_id = models.ForeignKey(Manager, on_delete=models.CASCADE, verbose_name='问题处理人id', null=True,
                                       blank=True)
    sugg_status = models.BooleanField(default=False, verbose_name='问题状态')
    sugg_content = models.TextField(max_length=200, verbose_name='问题反馈内容')
    sugg_staff_name = models.CharField(max_length=20, verbose_name='问题处理人')
    sugg_way = models.CharField(max_length=10, verbose_name='问题处理类型')
    sugg_handle_time = models.DateTimeField(auto_now=True, verbose_name='问题解决时间')
    sugg_staff_tele = models.CharField(max_length=11, verbose_name='问题反馈人电话')
    sugg_treat = models.IntegerField(default=0)
    # 用户二次反馈
    sugg_feedback = models.IntegerField(default=0)
    sugg_summary = models.CharField(max_length=100, default='')

    class Meta:
        managed = True
        db_table = "Suggestion"

    def save(self, *args, **kwargs):
        if not self.sugg_id:
            now = datetime.now()
            date_str = now.strftime("%Y%m%d")  # 当天日期部分

            # 获取最新的一条记录（无条件限制）
            last_record = Suggestion.objects.last()  # 按主键降序获取最后一条记录

            # 确定递增编号
            if last_record and last_record.sugg_id.startswith(f"J-{date_str}"):
                last_increment = int(last_record.sugg_id.split('-')[-1])  # 提取递增部分
                daily_increment = last_increment + 1
            else:
                daily_increment = 1  # 如果当天没有记录，编号从 1 开始

            # 拼接最终 ID
            self.sugg_id = f"J-{date_str}-{daily_increment:03d}"
        super().save(*args, **kwargs)


class SuggestionMedia(models.Model):
    sugg_media = models.ImageField(upload_to=generate_image_filename, null=True, blank=True, verbose_name='建议图片')
    sugg_list = models.ForeignKey(Suggestion, on_delete=models.CASCADE, verbose_name='建议表id')

    def save(self, *args, **kwargs):
        # 只有在 comp_media 存在且需要转换时才处理
        if self.sugg_media and not self.sugg_media.name.lower().endswith('.webp'):
            # 打开原始图片
            image = Image.open(self.sugg_media)
            output = BytesIO()
            # 保存为 WebP 格式
            image.save(output, format='WEBP', quality=85)
            output.seek(0)

            # 生成新的文件名
            file_name = generate_image_filename(self, self.sugg_media.name)
            # 使用生成的文件名保存图片
            self.sugg_media.save(file_name, ContentFile(output.read()), save=False)

        super().save(*args, **kwargs)


class SuggestionHandleMedia(models.Model):
    sugg_handle_media = models.ImageField(upload_to=generate_image_filename, null=True, blank=True,
                                          verbose_name='建议处理图')
    sugg_handle_list = models.ForeignKey(Suggestion, on_delete=models.CASCADE, verbose_name='建议表id')

    def save(self, *args, **kwargs):
        # 只有在 comp_media 存在且需要转换时才处理
        if self.sugg_handle_media and not self.sugg_handle_media.name.lower().endswith('.webp'):
            # 打开原始图片
            image = Image.open(self.sugg_handle_media)
            output = BytesIO()
            # 保存为 WebP 格式
            image.save(output, format='WEBP', quality=85)
            output.seek(0)

            # 生成新的文件名
            file_name = generate_image_filename(self, self.sugg_handle_media.name)
            # 使用生成的文件名保存图片
            self.sugg_handle_media.save(file_name, ContentFile(output.read()), save=False)

        super().save(*args, **kwargs)


class Complaint(models.Model):
    comp_sub_id = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='建议提交人id')
    comp_id = models.CharField(max_length=50, unique=True, editable=False, verbose_name='表单id')
    comp_name = models.CharField(max_length=20, null=False, verbose_name='建议提交人姓名')
    comp_user_tele = models.CharField(max_length=11, null=True, verbose_name='建议提交人电话')
    comp_title = models.CharField(max_length=20, verbose_name='投诉标题', blank=True, null=True)
    comp_text = models.TextField(max_length=100, null=True, verbose_name='建议描述')
    comp_site = models.CharField(max_length=100, null=False, verbose_name='建议地址')
    comp_sub_time = models.DateTimeField(auto_now_add=True, verbose_name='建议时间')
    comp_handle_id = models.ForeignKey(Manager, on_delete=models.CASCADE, null=True, blank=True,
                                       verbose_name='建议处理人id')
    comp_status = models.BooleanField(default=False, verbose_name='建议状态')
    comp_content = models.TextField(verbose_name='建议反馈内容')
    comp_staff_name = models.CharField(max_length=20, verbose_name='建议处理人')
    comp_way = models.CharField(max_length=10, verbose_name='建议处理类型')
    comp_handle_time = models.DateTimeField(auto_now=True, verbose_name='建议解决时间')
    comp_staff_tele = models.CharField(max_length=11, verbose_name='建议反馈人电话')
    comp_treat = models.IntegerField(default=0)
    # 用户二次反馈
    comp_feedback = models.IntegerField(default=0)
    comp_summary = models.CharField(max_length=100, default='')

    class Meta:
        managed = True
        db_table = "Complaint"

    def save(self, *args, **kwargs):
        if not self.comp_id:
            now = datetime.now()
            date_str = now.strftime("%Y%m%d")  # 当天日期部分

            # 获取最新的一条记录（无条件限制）
            last_record = Complaint.objects.last()  # 按主键降序获取最后一条记录

            # 确定递增编号
            if last_record and last_record.comp_id.startswith(f"T-{date_str}"):
                last_increment = int(last_record.comp_id.split('-')[-1])  # 提取递增部分
                daily_increment = last_increment + 1
            else:
                daily_increment = 1  # 如果当天没有记录，编号从 1 开始

            # 拼接最终 ID
            self.comp_id = f"T-{date_str}-{daily_increment:03d}"

        super().save(*args, **kwargs)


class ComplaintMedia(models.Model):
    comp_media = models.ImageField(upload_to=generate_image_filename, null=True, blank=True, verbose_name='建议图片')
    comp_list = models.ForeignKey(Complaint, on_delete=models.CASCADE, verbose_name='建议表id')

    def save(self, *args, **kwargs):
        # 只有在 comp_media 存在且需要转换时才处理
        if self.comp_media and not self.comp_media.name.lower().endswith('.webp'):
            # 打开原始图片
            image = Image.open(self.comp_media)
            output = BytesIO()
            # 保存为 WebP 格式
            image.save(output, format='WEBP', quality=85)
            output.seek(0)

            # 生成新的文件名
            file_name = generate_image_filename(self, self.comp_media.name)
            # 使用生成的文件名保存图片
            self.comp_media.save(file_name, ContentFile(output.read()), save=False)

        super().save(*args, **kwargs)


class ComplaintHandleMedia(models.Model):
    comp_handle_media = models.ImageField(upload_to=generate_image_filename, null=True, blank=True,
                                          verbose_name='建议处理图')
    comp_handle_list = models.ForeignKey(Complaint, on_delete=models.CASCADE, verbose_name='建议表id')

    def save(self, *args, **kwargs):
        # 只有在 comp_media 存在且需要转换时才处理
        if self.comp_handle_media and not self.comp_handle_media.name.lower().endswith('.webp'):
            # 打开原始图片
            image = Image.open(self.comp_handle_media)
            output = BytesIO()
            # 保存为 WebP 格式
            image.save(output, format='WEBP', quality=85)
            output.seek(0)

            # 生成新的文件名
            file_name = generate_image_filename(self, self.comp_handle_media.name)
            # 使用生成的文件名保存图片
            self.comp_handle_media.save(file_name, ContentFile(output.read()), save=False)

        super().save(*args, **kwargs)


class Color(models.Model):  # 该类待定
    color_text = models.TextField(verbose_name='社区风采文字')
    color_file = models.FileField(verbose_name='社区风采图片')

    class Meta:
        managed = True
        db_table = "Color"


class Warn(models.Model):
    warn_text = models.TextField(null=True, verbose_name='温馨提示')

    class Meta:
        managed = True
        db_table = "Warn"


class Hotline(models.Model):
    hotline_who = models.CharField(max_length=20, verbose_name='热线电话名称')
    hotline_tele = models.CharField(max_length=20, verbose_name='热线电话号码')

    class Meta:
        managed = True
        db_table = "Hotline"


def cover_upload_to(instance, filename):
    # 获取当前日期和时间，精确到分钟，格式化为 YYYY年MM月DD日HH时MM分
    current_datetime = timezone.now().strftime('%Y-%m-%d-%H-%M')
    # 获取原始文件扩展名
    file_extension = os.path.splitext(filename)[1]
    # 生成新的文件名，使用日期和扩展名
    new_filename = f"{current_datetime}{file_extension}"
    # 返回文件保存的路径
    return os.path.join('files', new_filename)


class Cover(models.Model):
    cover_file = models.FileField(verbose_name='主页封面', upload_to=cover_upload_to)

    def save(self, *args, **kwargs):
        if self.cover_file:
            try:
                # 获取原始文件扩展名
                file_extension = os.path.splitext(self.cover_file.name)[1]
                print(file_extension)
                # 打开原始图片
                image = Image.open(self.cover_file)
                print(image)
                # 调整图片尺寸
                image1 = image.resize((1366, 768), Image.LANCZOS)

                output = BytesIO()

                # 处理不同格式的图片
                if self.cover_file.name.lower().endswith(('.png', '.jpg', '.jpeg')):
                    image1.save(output, format='WEBP', quality=85)  # 保存为 WebP 格式
                    output.seek(0)

                    # 生成新的 WebP 文件名
                    file_name = cover_upload_to(self, self.cover_file.name).replace(file_extension, '.webp')
                    print(file_name)
                    self.cover_file.save(file_name, ContentFile(output.read()), save=False)

            except Exception as e:
                # 处理异常，记录日志
                print(f"Error processing image: {e}")

        super().save(*args, **kwargs)

    class Meta:
        managed = True
        db_table = "Cover"


class LimitTable(models.Model):
    limit_num = models.CharField(max_length=100, blank=False, null=True, default='未填写')

    class Meta:
        managed = True
        db_table = "LimitNew"


class Frequency(models.Model):
    freq_sum = models.IntegerField(default=0, verbose_name='访问量（总）')

    class Meta:
        managed = True
        db_table = "Frequency"


class Background(models.Model):
    back_file = models.ImageField(verbose_name='主页封面', upload_to='picture')

    class Meta:
        managed = True
        db_table = "Background"
